package com.qf.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.service.SearchService;
import com.qf.util.SearchPojo;
import com.qf.util.SmsStatusDTO;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 何星宇
 * @version V1.0
 * @Date 2021/11/25 19:20
 */
@Service
public class SearchServiceImpl implements SearchService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 根据条件查询日志集合数据返回
     * @param searchPojo
     */
    @Override
    public List<Map> searchLog(SearchPojo searchPojo) throws IOException {
        //创建request
        SearchRequest request = new SearchRequest();
        request.indices("sms_submit_log2021");
        //封装查询数据到request中
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        //条件查询
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (searchPojo.getClientID()!=null){
            boolQueryBuilder.must(QueryBuilders.matchQuery("clientID", searchPojo.getClientID()));
        }
        if (!StringUtils.isEmpty(searchPojo.getKeyword())) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("messageContent", searchPojo.getKeyword()));
        }
        if (!StringUtils.isEmpty(searchPojo.getMobile())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("destMobile", searchPojo.getMobile()));
        }
        if (searchPojo.getStartTime()!=null){
            boolQueryBuilder.must(QueryBuilders.rangeQuery("startTime").gte(searchPojo.getStartTime()));
        }
        if (searchPojo.getEndTime()!=null){
            boolQueryBuilder.must(QueryBuilders.rangeQuery("sendTime").lte(searchPojo.getEndTime()));
        }



        //高亮查询
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.fragmentSize(2);
        if (!StringUtils.isEmpty(searchPojo.getHighLightPreTag())&&!StringUtils.isEmpty(searchPojo.getHighLightPostTag())){
            highlightBuilder.preTags(searchPojo.getHighLightPreTag());
            highlightBuilder.postTags(searchPojo.getHighLightPostTag());
        }
        highlightBuilder.field("messageContent");


        //分页查询
        if (searchPojo.getStart()!=null){
            sourceBuilder.from(searchPojo.getStart());
        }
        if (searchPojo.getRows()!=null){
            sourceBuilder.size(searchPojo.getRows());
        }
//        sourceBuilder.sort("startTime", SortOrder.DESC);

        sourceBuilder.query(boolQueryBuilder);
        sourceBuilder.highlighter(highlightBuilder);

        //将sourceBuilder查询条件封装进request
        request.source(sourceBuilder);
        //发送，接收响应
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        List<Map> result = new ArrayList<>();
        for (SearchHit hit : response.getHits().getHits()) {
            HighlightField messageContent = hit.getHighlightFields().get("messageContent");
            Map<String, Object> map = hit.getSourceAsMap();
            if (messageContent!=null){
                map.put("messageContent", messageContent.getFragments()[0].toString());
            }
            result.add(map);
        }
        return result;
    }

    /**
     * 根据条件查询日志总条数
     * @param searchPojo
     */
    @Override
    public Long searchLogCount(SearchPojo searchPojo) throws IOException {
        //获取客户id
        Integer clientID = searchPojo.getClientID();
        SearchRequest request = new SearchRequest();
        request.indices("sms_submit_log2021");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();


        //条件查询
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (searchPojo.getClientID()!=null){
            boolQueryBuilder.must(QueryBuilders.matchQuery("clientID", searchPojo.getClientID()));
        }
        if (!StringUtils.isEmpty(searchPojo.getKeyword())) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("messageContent", searchPojo.getKeyword()));
        }
        if (!StringUtils.isEmpty(searchPojo.getMobile())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("destMobile", searchPojo.getMobile()));
        }
        if (searchPojo.getStartTime()!=null){
            boolQueryBuilder.must(QueryBuilders.rangeQuery("startTime").gte(searchPojo.getStartTime()));
        }
        if (searchPojo.getEndTime()!=null){
            boolQueryBuilder.must(QueryBuilders.rangeQuery("sendTime").lte(searchPojo.getEndTime()));
        }

        sourceBuilder.query(boolQueryBuilder);
        //将sourceBuilder查询条件封装进request
        request.source(sourceBuilder);
        //发送，接收响应
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        return response.getHits().getTotalHits().value;
    }

    /**
     * 统计报表查询
     * @param smsStatusDTO
     */
    @Override
    public Map<String, Long> statSendStatus(SmsStatusDTO smsStatusDTO) throws IOException {
        //创建request
        SearchRequest request = new SearchRequest();
        request.indices("sms_submit_log2021");

        //时间条件
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("sendTime");
        if (smsStatusDTO.getClientID()!=null){
            boolQueryBuilder.must(QueryBuilders.matchQuery("clientID", smsStatusDTO.getClientID()));
        }
        if (smsStatusDTO.getStartTime()!=null){
            rangeQueryBuilder.gte(smsStatusDTO.getStartTime());
        }
        if (smsStatusDTO.getEndTime()!=null){
            rangeQueryBuilder.lte(smsStatusDTO.getEndTime());
        }
        boolQueryBuilder.must(rangeQueryBuilder);

        TermsAggregationBuilder aggregationBuilder = AggregationBuilders.terms("Terms").field("reportState");

        //封装进request
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(boolQueryBuilder);
        sourceBuilder.aggregation(aggregationBuilder);
        request.source(sourceBuilder);

        //发送
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        Terms terms = response.getAggregations().get("Terms");
        Map<String, Long> result = new HashMap<>();
        for (Terms.Bucket bucket : terms.getBuckets()) {
            result.put(String.valueOf(bucket.getKey()),bucket.getDocCount());
        }

        return result;
    }
}
